<template>
  <div class="login_page">
    <Header />
    <div class="container mt-8">
      <div class="m-card" :class="{'is-mobile': loginFlag.isMobile}">
        <div class="login-label">Inicio teléfono</div>

        <div class="form-wrapper">
          <div class="row cf">
            <!-- <div class="label">账号</div> -->
            <div class="input-box">
              <input
                v-model="formData.mobile"
                type="text"
                class="input spec"
                placeholder="Teléfono"
                placeholder-class="m-input-placeholder"
                maxlength="9"
                @change="handleTimerChange"
              />
            </div>
          </div>
          <div class="row m-cf">
            <!-- <div class="label">验证码</div> -->
            <input
              v-model="formData.verifyCode"
              type="text"
              maxlength="4"
              class="input valid m-fl"
              placeholder="Código"
              placeholder-class="m-input-placeholder"
            />
            <div class="send-btn m-fr" @click="sendVerifySms">
              {{ verifyBtn.text }}
            </div>
          </div>
          <!-- <div class="row">
            <el-checkbox
              :true-label="7"
              :false-label="1"
              v-model="formData.keepLogin"
              >7天自动Iniciar sesión</el-checkbox
            >
          </div> -->
          <div class="login-btn" @click="login">{{ loginText }}</div>
          <div class="row notice">
            Si su número de teléfono no está registrado, el sistema creará
            automáticamente un usuario para usted
          </div>
          <div class="col login-checkbox-container">
            <div>
              <el-checkbox class="login-el-checkbox" v-model="loginFlag.agreement" @change="agreementChange"
                >Declaro que he leído, entendido y acepto los Términos y Condiciones, la política de cancelación y la política de reembolso/devolución.</el-checkbox
              >
            </div>
            <div class="agreement-list">
              <div>
                <el-checkbox class="login-el-checkbox-2" v-model="loginFlag.agreement1" @change="agreement1Change"></el-checkbox>
                <span class="highlight" @click="jump2policyHref">Acuerdo de Privacidad</span>
              </div>
              <div>
                <el-checkbox class="login-el-checkbox-2" v-model="loginFlag.agreement2" @change="agreement2Change"></el-checkbox>
                <span class="highlight" @click="jump2agreementHref">Acuerdo de Usuario</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Header from "@/components/layout/header.vue";

const IsChecked = '1'
const NoChecked = '0'

function isAgreementCheck(key) {
  const v = sessionStorage.getItem(key)
  if (v && v === IsChecked) {
    return true
  }
  return false
}

export default {
  components: {
    Header,
  },
  data() {
    return {
      verifyBtn: {
        text: "Obtener",
        time: 60,
        timer: null,
        pending: false,
      },

      formData: {
        mobile: "",
        verifyType: 1,
        verifyCode: "",
        longitude: -360,
        latitude: -360,
        keepLogin: 7,
      },

      loginFlag: {
        pending: false,
        agreement: isAgreementCheck('login_agreement1') && isAgreementCheck('login_agreement2'),
        agreement1: isAgreementCheck('login_agreement1'),
        agreement2: isAgreementCheck('login_agreement2'),
        isMobile: false,
      },
      loginText: "Iniciar sesión",
    };
  },
  created() {
    const defaultInnerWidth = window.innerWidth;
    if (defaultInnerWidth < 700) {
      this.loginFlag.isMobile = true;
    }
    var that = this;
    window.onresize = function () {
      const resizeInnerWidth = window.innerWidth;
      if (resizeInnerWidth < 700) {
        that.loginFlag.isMobile = true;
      } else {
        that.loginFlag.isMobile = false;
      }
    };
  },
  methods: {
    startTimer() {
      this.verifyBtn.timer = setInterval(() => {
        if (this.verifyBtn.time == 1) {
          this.verifyBtn.text = "Obtener nuevamente";
          this.verifyBtn.time = 60;
          this.clearTimer();
        } else {
          this.verifyBtn.time--;
          this.verifyBtn.text = this.verifyBtn.time + "s";
        }
      }, 1000);
    },
    clearTimer() {
      this.verifyBtn.pending = false;
      clearInterval(this.verifyBtn.timer);
    },
    sendVerifySms() {
      if (this.verifyBtn.pending) return;
      if (!this.$util.validatePhone(this.formData.mobile)) {
        return this.$message.warning(
          "Proporciona la información correcta"
        );
      }
      this.verifyBtn.text = "Enviando...";
      this.verifyBtn.pending = true;
      this.$http
        .post(this.$api.sendVerifySms, this.formData)
        .then((res) => {
          if (res.resultCode == 200) {
            this.startTimer();
          } else {
            this.verifyBtn.pending = false;
          }
        })
        .catch(() => {
          this.verifyBtn.pending = false;
        });
    },
    handleTimerChange() {
      this.verifyBtn.text = "Obtener";
      this.clearTimer();
    },
    login() {
      if (this.loginFlag.pending) return;
      if (!this.$util.validatePhone(this.formData.mobile)) {
        return this.$message.warning(
          "Proporciona la información correcta"
        );
      }
      if (!this.$util.validateVerifyCode(this.formData.verifyCode)) {
        return this.$message.warning(
          "Por favor, introduzca el código de verificación correcto"
        );
      }
      if (!this.loginFlag.agreement) {
        return this.$message.warning("Por favor, marque el acuerdo de usuario");
      }
      this.loginFlag.pending = true;
      this.loginText = "Iniciar sesión...";
      this.$http
        .post(this.$api.registerOrLogin, this.formData)
        .then((res) => {
          if (res.resultCode == 200) {
            const { userId, token, isRegister } = res.data;
            if (isRegister) {
              // this.$adjust.trackEvent({
              //   eventToken: "ysc804",
              // });
              this.$trackPixel('Register')
            }
            const { tokenValue } = token;
            this.$state["LOGIN_INFO"] = { userId, tokenValue };
            this.getUserInfo();
          } else {
            this.loginFlag.pending = false;
            this.handleTimerChange();
            this.loginText = "Iniciar sesión";
          }
        })
        .catch(() => {
          this.loginFlag.pending = false;
          this.handleTimerChange();
          this.loginText = "Iniciar sesión";
        });
    },
    getUserInfo() {
      this.$http
        .post(this.$api.getUserInfo)
        .then((res) => {
          if (res.resultCode == 200) {
            this.$state["USER_INFO"] = res.data;
            this.$state["REFRESH_SIGN"] = true;
            this.$router.replace({
              name: "HomeIndex",
            });
          }
          this.loginFlag.pending = false;
          this.handleTimerChange();
          this.loginText = "Iniciar sesión";
        })
        .catch(() => {
          this.loginFlag.pending = false;
          this.handleTimerChange();
          this.loginText = "Iniciar sesión";
        });
    },

    jump2policyHref() {
      this.$util.openIframe(this.$state["CONFIG_INFO"].policyHref);
    },
    jump2agreementHref() {
      this.$util.openIframe(this.$state["CONFIG_INFO"].conditionsHref);
    },
    agreementChange(isCheck) {
      if (isCheck) {
        sessionStorage.setItem('login_agreement1', IsChecked)
        sessionStorage.setItem('login_agreement2', IsChecked)
        this.loginFlag.agreement1 = true
        this.loginFlag.agreement2 = true
      } else {
        sessionStorage.setItem('login_agreement1', NoChecked)
        sessionStorage.setItem('login_agreement2', 0)
        this.loginFlag.agreement1 = false
        this.loginFlag.agreement2 = false
      }
    },
    agreement1Change(isCheck) {
      sessionStorage.setItem('login_agreement1', isCheck ? IsChecked : NoChecked)
      if (isCheck && this.loginFlag.agreement2) {
        this.loginFlag.agreement = true
      } else {
        this.loginFlag.agreement = false
      }
    },
    agreement2Change(isCheck) {
      sessionStorage.setItem('login_agreement2', isCheck ? IsChecked : NoChecked)
      if (isCheck && this.loginFlag.agreement1) {
        this.loginFlag.agreement = true
      } else {
        this.loginFlag.agreement = false
      }
    },
  },
  beforeDestroy() {
    this.handleTimerChange();
  },
};
</script>



<style lang="scss" scoped>
.m-card {
  position: absolute;
  top: 7rem;
  left: 0;
  right: 0;
  width: 42rem;
  margin: auto;
  border-radius: 24px;
  background-color: #fff;
  padding: 60px 50px;
  text-align: center;
  &.is-mobile {
    width: 100%;
    background-color: transparent;
    padding: 0;
  }
}
.login-label {
  position: relative;
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 50px;
  &::after {
    content: "";
    position: absolute;
    bottom: -10px;
    left: 0;
    right: 0;
    margin: 0 auto;
    width: 187px;
    height: 3px;
    background-color: #fb563d;
  }
}
.form-wrapper {
  margin: 30px 20px 20px;
  text-align: center;
  .row {
    width: 330px;
    margin: 0 auto 8px;
    .input-box {
      position: relative;
      width: 100%;
      &::before {
        content: "+34";
        position: absolute;
        left: 10px;
        top: 11px;
        color: #fb563d;
        z-index: 99;
      }
    }
    .label {
      font-size: 15px;
      float: left;
      width: 70px;
      line-height: 40px;
      margin-bottom: 6px;
    }
    .input {
      position: relative;
      float: left;
      // width: calc(100% - 104px);
      width: 100%;
      height: 46px;
      padding: 0 12px;
      border: 1px solid #e9e9e9;
      border-radius: 6px;
      &.spec {
        padding: 0 12px 0 46px;
      }
      &.valid {
        width: calc(100% - 108px);
      }
    }
    .send-btn {
      width: 100px;
      height: 46px;
      line-height: 46px;
      text-align: center;
      color: #fb5341;
      background-color: #ffffff;
      border-radius: 6px;
      border: 1px solid #e9e9e9;
      margin-left: 8px;
      cursor: pointer;
      &.active {
        color: #ffffff;
        background-color: var(--c-theme);
      }
      .code-pic {
        width: 100%;
        height: 41px;
      }
    }
  }
  .login-btn {
    width: 330px;
    margin: 56px auto 0;
    height: 44px;
    line-height: 44px;
    text-align: center;
    font-size: 16px;
    font-weight: 500;
    color: #ffffff;
    background: linear-gradient(to bottom, #fa5142, #ff7422);
    border-radius: 4px;
    cursor: pointer;
  }
  .notice {
    width: 330px;
    margin: 12px auto 20px;
    text-align: left;
    font-size: 14px;
    color: #999;
    line-height: 20px;
  }
  .register-btn {
    padding: 8px 0 10px;
    font-size: 12px;
    text-align: center;
    color: #999999;
  }
  .agreement-wrapper {
    font-size: 14px;
    margin-top: 16px;
    text-align: center;
    color: #999999;
    .check {
      padding: 6px 4px 10px 10px;
      width: 12px;
      height: 12px;
      margin-bottom: -11px;
      ::v-deep {
        .van-icon {
          font-size: 15px;
        }
      }
      &.active {
        color: var(--c-theme);
      }
    }
    .rule {
      color: var(--c-theme);
    }
  }
}
.highlight {
  color: #ff7422;
  cursor: pointer;
}

.login-checkbox-container {
  width: 330px;
  margin: 0 auto;
  padding: 0;
  text-align: left;
}

.agreement-list {
  padding-left: 20px;
}

</style>

<style lang="scss">
.login_page {
  .login-el-checkbox {
    .el-checkbox__label {
      white-space: initial;
      text-align: left;
      vertical-align: top;
    }
  }

  .login-el-checkbox-2 {
    margin-right: 6px;
  }
}
</style>